/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { PureComponent } from "react";
import { connect } from "dva";
import PageHeaderLayout from "@/layouts/PageHeaderLayout";
import { Row, Col, Button, Input, Form, Table, Radio, Popconfirm, Affix } from "antd";
import { debounce } from "lodash";
import styles from "./allot.less";
import AllotCourierModal, { AllotCourier } from "@/components/AllotCourierModal";
import { dateCalendar, timeDistance } from "@/utils/utils";
import router from "umi/router";

const { Group: RadioGroup, Button: RadioButton } = Radio;
const FormItem = Form.Item;
const defaultShrink = "fold";
const defaultTarget = "published";

// 搜索表单
@Form.create()
class TopSearchForm extends PureComponent {
  handleSearch = debounce(() => {
    const { onSearch } = this.props;
    if (onSearch) {
      onSearch();
    }
  }, 500, {
    leading: true,
    trailing: false
  })

  render() {
    const { form, loading } = this.props;
    return (
      <Form style={{ textAlign: "right" }} layout="inline">
        <FormItem>
          {form.getFieldDecorator("searchc")(<Input placeholder="下单客户姓名/手机号" />)}
        </FormItem>
        <FormItem>
          {form.getFieldDecorator("searchd")(<Input placeholder="配送员姓名/手机号" />)}
        </FormItem>
        <FormItem>
          <Button type="primary" icon="search" loading={loading} onClick={this.handleSearch}>
            查询
          </Button>
        </FormItem>
      </Form>
    );
  }
}

@connect(({ allot, loading, global }) => {
  return {
    allotTarget: global.allotTarget,
    allotShrink: global.allotShrink,
    getting: loading.effects["allot/getList"],
    allot
  };
})
export default class Allot extends PureComponent {
  constructor() {
    super();
    this.state = {
      currentCourierData: null
    };
  }

  componentWillMount() {
    const {
      allotTarget,
      location: { hash }
    } = this.props;
    this.allotShrink = hash.substring(1) || defaultShrink;
    this.currentStatus = allotTarget || defaultTarget;
  }

  componentDidMount() {
    this.getCount();
    this.getList();
  }

  // 状态列表
  allotStatusList = [
    {
      label: "新订单-待抢单",
      key: "published"
    },
    {
      label: "已接单-待取件",
      key: "accepted"
    },
    {
      label: "已取件-待送达",
      key: "acquired"
    },
    {
      label: "已完成",
      key: "arrived"
    },
    {
      label: "已取消",
      key: "canceled"
    }
  ];

  // 创建表格列
  createColumns = () => {
    const { currentStatus: status } = this;
    const columns = [
      {
        title: "下单时间",
        dataIndex: "publishTime",
        width: 150,
        render: dateCalendar
      },
      {
        title: "预定取货时间",
        dataIndex: "appointTime",
        width: 150,
        render: dateCalendar
      },
      {
        title: "下单客户",
        dataIndex: "senderName",
        width: 150,
        render(val, record) {
          return `${val}\n${record.senderMobile}`;
        }
      },
      {
        title: "取件地址",
        dataIndex: "senderAddress",
        width: 150,
        // render(val, record) {
        //   return  (<span>
        //     { record.goodsWay == "send" ? record.senderAddress : record.receiveAddress}
        //     </span>)
        // }
      },
      {
        title: "送达地址",
        dataIndex: "receiveAddress",
        width: 150,
        // render(val, record) {
        //   return  (<span>
        //     { record.goodsWay == "send" ? record.receiveAddress : record.senderAddress}
        //     </span>)
        // }
      },
      {
        title: "距离（公里）",
        dataIndex: "pathDistance",
        render: text => {
          return (
            <span>{Math.round(text / 1000 * 100) / 100}</span>
          );
        }
      },
      {
        title: "重量（千克）",
        dataIndex: "goodsWeight"
      },
      {
        // receipts 财务确认的收款金额 earningss 快递员的收入
        title: "配送费（元）",
        dataIndex: "freight"
      },
      {
        title: "物品类型",
        dataIndex: "goodsInfo"
      },
      {
        title: "配送员",
        dataIndex: "courierName",
        render(val, record) {
          if (val) {
            return (
              <div>
                {val}
                <br />
                {record.courierMobile}
              </div>
            );
          } else {
            return "-";
          }
        }
      },
      {
        title: "订单编号",
        dataIndex: "orderNumber",
        width: 150
      },
      {
        title: "备注",
        dataIndex: "goodsNote",
        width: 150
      }
    ];
    if (status === "published" || status === "accepted" || status === "acquired") {
      const buttonText = {
        published: "分配",
        accepted: "改派"
      };
      // 未完成
      if (status === "accepted") {
        // 已接单，待取件
        columns[0] = {
          ...columns[0],
          title: "接单时间",
          dataIndex: "acceptTime"
        };
      } else if (status === "acquired") {
        //  已取件，待送达
        columns[0] = {
          ...columns[0],
          title: "取件时间",
          dataIndex: "acquireTime"
        };
        columns[1] = {
          ...columns[1],
          title: "已取件时长",
          dataIndex: "pickup_time_distance",
          render(val, record) {
            return timeDistance(record.acquireTime);
          }
        };
      }
      columns.push({
        title: "操作",
        dataIndex: "id",
        fixed: "right",
        width: 150,
        render: (val, record) => {
          return (
            <div className="allot-button-wrap">
              {buttonText[status] && (
                <Button
                  size="small"
                  ghost
                  type="primary"
                  onClick={() => {
                    this.currentAllotData = record;
                    this.setState({
                      visible: true
                    });
                  }}
                >
                  {buttonText[status]}
                </Button>
              )}
              <Popconfirm
                title="是否取消该订单？"
                okText="是"
                cancelText="否"
                onConfirm={() => {
                  this.cancelOrder(record);
                }}
              >
                <Button size="small" ghost type="danger">
                  取消
                </Button>
              </Popconfirm>
            </div>
          );
        }
      });
    } else if (status === "arrived") {
      //  已完成
      columns[0] = {
        ...columns[0],
        title: "送达时间",
        dataIndex: "arriveTime"
      };
      columns[1] = {
        ...columns[1],
        title: "总时长",
        dataIndex: "arrive_time_distance",
        render(val, record) {
          return timeDistance(record.arriveTime, record.acceptTime);
        }
      };
    } else {
      //  已取消
      columns[0] = {
        ...columns[0],
        title: "取消时间",
        dataIndex: "cancelTime"
      };
      columns.splice(1, 1);
    }
    return columns;
  };

  // 获取统计数据
  getCount = () => {
    this.props.dispatch({
      type: "allot/getCount"
    });
  };

  // 刷新
  handleRefresh = () => {
    this.topForm && this.topForm.props.form.resetFields();
    this.getCount();
    this.getList(null, true);
  };

  // 切换状态
  handleStatusChange = e => {
    const { value } = e.target;
    this.currentStatus = value;
    this.getList({
      page: 1
    });
    // 全局记录当前target
    this.props.dispatch({
      type: "global/save",
      payload: {
        allotTarget: value
      }
    });
  };

  // 取消订单
  cancelOrder = record => {
    const { courierId: courier_id, orderNumber: order_id, status } = record;
    this.props
      .dispatch({
        type: "allot/cancelOrder",
        payload: {
          order_id,
          courier_id,
          cancel: status
        }
      })
      .then(res => {
        if (res.code == 0) {
          this.getList();
        }
      });
  };

  // 获取调度列表
  getList = (data, force) => {
    const formData = this.topForm ? this.topForm.props.form.getFieldsValue() : null;
    this.props.dispatch({
      type: "allot/getList",
      payload: {
        page: 1,
        ...formData,
        target: this.currentStatus,
        ...data
      },
      force
    });
  };

  // 收缩左侧列表
  handleShrink = () => {
    const { dispatch, allotShrink = this.allotShrink } = this.props;
    const nextShrink = allotShrink === "fold" ? "unfold" : "fold";
    dispatch({
      type: "global/save",
      payload: {
        allotShrink: nextShrink
      }
    });
    router.replace(`/delivery/allot#${nextShrink}`);
  };

  render() {
    const {
      allotShrink = this.allotShrink,
      getting,
      allot: { allotData, countData }
    } = this.props;
    const { visible } = this.state;
    const allotDataTarget = allotData[this.currentStatus];
    const allotTable = {
      dataSource: allotDataTarget && allotDataTarget.list,
      pagination: allotDataTarget
        ? {
          current: 1 * allotDataTarget.page,
          total: 1 * allotDataTarget.count,
          showQuickJumper: true,
          pageSize: 1 * allotDataTarget.pageSize || 20,
          onChange: page => {
            this.getList({
              page
            });
          }
        }
        : false
    };
    return (
      <PageHeaderLayout title="订单调度" wrapperClassName={styles.allot}>
        <Row gutter={12} className={`allot-row allot-shrink-${allotShrink}`}>
          <Col xs={24} sm={6} className="allot-col-left">
            <Affix offsetTop={80} className="allot-affix-wrapper">
              <AllotCourier onRefresh={this.handleRefresh} />
              <Button
                onClick={this.handleShrink}
                className="allot-shrink-bar"
                icon={`menu-${allotShrink}`}
              />
            </Affix>
          </Col>
          <Col xs={24} sm={18} className="allot-col-right">
            <TopSearchForm
              wrappedComponentRef={node => (this.topForm = node)}
              loading={getting}
              onSearch={() => {
                this.getList(null, true);
              }}
            />
            <div className="rightTable">
              <FormItem>
                <RadioGroup
                  onChange={this.handleStatusChange}
                  defaultValue={this.currentStatus}
                  buttonStyle="solid"
                  className="status-radio"
                >
                  {this.allotStatusList.map(({ label, key }) => (
                    <RadioButton key={key} value={key}>
                      <p>{label}</p>
                      <p>
                        单量：
                        {countData ? countData[key].num : 0}
                      </p>
                    </RadioButton>
                  ))}
                </RadioGroup>
              </FormItem>
              <Table
                rowKey="orderNumber"
                loading={getting}
                scroll={{
                  x: 1700
                }}
                columns={this.createColumns()}
                {...allotTable}
              />
            </div>
          </Col>
        </Row>
        <AllotCourierModal
          currentAllotData={this.currentAllotData}
          onVisibleChange={visible => {
            this.setState({
              visible
            });
          }}
          onAssign={res => {
            if (res.code == 0) {
              this.getList();
            }
          }}
          visible={visible}
        />
      </PageHeaderLayout>
    );
  }
}
